<?php

/**

 * tpshop

 * ============================================================================

 * * 版权所有 2015-2027 深圳搜豹网络科技有限公司，并保留所有权利。

 * 网站地址: http://www.tp-shop.cn

 * ----------------------------------------------------------------------------

 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .

 * 不允许对程序代码以任何形式任何目的的再发布。

 * ============================================================================


 */

namespace app\mobile\controller;

use app\home\logic\UsersLogic;
use app\home\logic\WechatLogic;
use think\Controller;
use think\Session;
use think\Db;
use Think\Log;
use pdo;


class MobileBase extends Controller {

    public $session_id;

    public $dltoken;

    public $weixin_config=array();

    public $cateTrre = array();

    /*

     * 初始化操作

     */

    public function _initialize() {

        Session::start();

        header("Cache-control: private");  // history.back返回后输入框值丢失问题 

        $this->session_id = session_id(); // 当前的 session_id

        define('SESSION_ID',$this->session_id); //将当前的session_id保存为常量，供其它方法调用
        // var_dump(gpslocation_city("30.619629670586","114.20728613306"));
        // 判断当前用户是否手机    
   
        if(isMobile())

            cookie('is_mobile','1',3600); 

        else 

            cookie('is_mobile','0',3600);


        //获取鼎联token
       $dltoken=I('get.dltoken');
       if($dltoken){
            if($_SESSION['dltoken']!=$dltoken){
              session('user',null);
            }
            $_SESSION['dltoken']=$dltoken;
       }

       

       $this->weixin_config= M('wx_user')->where(array('appid'=>$_SESSION['dltoken']))->find(); //获取当前商户微信配置
       $this->assign('weixin_config', $this->weixin_config); 

        /*更新缓存中用户信息*/
       //session('user',null);
        if (session('?user')) {
            $user = session('user');
            $user = M('users')->where(array('user_id'=>$user['user_id']))->find();
            if($user['appid']!=$_SESSION['dltoken']){
              $openid=M('users')->where(array('relevance_id'=>$user['user_id'],'appid'=>$_SESSION['dltoken']))->getfield('openid');
              $user['openid']=$openid;
            }
           // echo"<script>alert(".$user['user_id'].")</script>";
           /* if(!$user['dlopenid']&&is_array($user)){
                $Wechat = new WechatLogic();
                $dlconfig= M('wx_user')->where(array('appid'=>'wx0c30f2ddb510d331'))->cache(true)->find();
                $Wechat->set_config($dlconfig);
                $dlopenid= $Wechat->getOpenId();
                M('users')->where("user_id", $user['user_id'])->save(array('dlopenid'=>$dlopenid));
                $user['dlopenid']=$dlopenid;
            }*/
            session('user', $user);  //覆盖session 中的 user
            $this->user = $user;
            $this->user_id = $user['user_id'];
            $this->assign('user', $user); //存储用户信息
            //var_dump(session('user'));
        }


        //微信浏览器

       //session('issubscribe',null);

        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger') && empty($this->user['openid'])){

            if(is_array($this->weixin_config) && $this->weixin_config['wait_access'] == 1){

                //$wxuser = $this->GetOpenid(); //授权获取openid以及微信用户信息
                //echo"<script>alert('weixin')</script>";

                //微信自动登录                             
                $Wechat = new WechatLogic();
                $wxconfig[]= M('wx_user')->where(array('appid'=>C('DL_APPID')))->cache(true)->find();
                $wxconfig[]=$this->weixin_config;
                $Wechat->Getcode_two($wxconfig);
                $openids=$_SESSION['openids'];
                //$openids=$Wechat->GetOpenid_two($wxconfig);
                $dlopenid=$openids[0];
                $openid=$openids[1];

                if(!$dlopenid){
                  $this->error('网络异常4001');
                  Log::record('[error_log][dlopenid获取异常][openid:'+$openid+']');
                }
                if(!$openid){
                  $this->error('网络异常4002');
                  Log::record('[error_log][openid获取异常][dlopenid:'+$openid+']');
                }
                $user= M('users')->where("openid", $openid)->order('user_id asc')->find();


                if($user){
                    /*如果该用户openid可以查询到，分两种情况：一种是不存在dlopenid直接导入数据库的用户，另外一种是存在dlopenid正常用户*/
                    if($user['dlopenid']){
                      if($user['relevance_id']==0){//如果关联id为0，说明主账号

                      }elseif($user['relevance_id']>0){//如果关联id大于0，说明为副账号
                        $user=M('users')->where("user_id", $user['relevance_id'])->find();//根据关联id查询出主账号的信息
                      }else{//账号异常4003
                        $this->error('网络异常4003');
                        Log::record('[error_log][relevance_id写入异常][openid:'+$openid+']');
                      }
                    }else{
                      if($user['relevance_id']==0){//说明是导入用户或者新关注客户
                        //查询数据库之前是否已经存在账户，如果存在则关联到之前的账户
                        $user2=M('users')->where('dlopenid',$dlopenid)->find();
                        if($user2){
                           $dataa['relevance_id'] =$user2['user_id'];
                        }
                        $dataa['dlopenid'] =$dlopenid;
                        M('users')->where("user_id", $user['user_id'])->save($dataa);
                        $user=M('users')->where("user_id", $user2['user_id'])->find();
                      }elseif($user['relevance_id']>0){//如果关联id大于0，说明为副账号
                        $user=M('users')->where("user_id", $user['relevance_id'])->find();//根据关联id查询出主账号的信息
                      }else{//账号异常4004
                        $this->error('网络异常4004');
                        Log::record('[error_log][relevance_id写入异常][openid:'+$openid+']');
                      }
                    }
                    
                }else{
                    //如果openid未查询到记录,则插入一条记录
                    $userinfo= $Wechat->getUserInfo($openid);
                    $userinfo['appid'] = $this->weixin_config['appid'];
                    $userinfo['dlopenid'] =$dlopenid;
                    //查询数据库之前是否已经存在账户，如果存在则关联到之前的账户
                    $user=M('users')->where('dlopenid',$dlopenid)->find();
                    if($user){
                      //var_dump('nihao1');
                       $userinfo['relevance_id'] =$user['user_id'];
                    }
                   
                    $logic = new UsersLogic();
                    $user_id=$logic->save_userdata($userinfo,'insert');
                    
                  /*  if(!$user){
                    //会员注册赠送积分升级等级
                    update_user_level($user['user_id']);
                    $pay_points = tpCache('basic.reg_integral');
                    accountLog($user['user_id'], 0,$pay_points, '会员注册赠送积分',0,'reg'); // 记录日志流水
                    }*/
                }
                    $user['openid']=$openid;
                    $this->user=$user;
                    session('user',$this->user);

                    setcookie('user_id',$this->user['user_id'],null,'/');

                    setcookie('is_distribut',$this->user['is_distribut'],null,'/');

                    setcookie('uname',$this->user['nickname'],null,'/'); 
                    $this->assign('user', $user); //存储用户信息                   

                    // 登录后将购物车的商品的 user_id 改为当前登录的id

                    M('cart')->where("session_id", $this->session_id)->save(array('user_id'=>$this->user['user_id']));

                    $cartLogic = new \app\home\logic\CartLogic();

                    $cartLogic->login_cart_handle($this->session_id,$this->user['user_id']);  //用户登录后 需要对购物车 一些操作
                    $this->user_id = $this->user['user_id'];
                

            }



        }

        $auth=M('auth')->where('user_id',$this->user_id)->find();
        $this->auth=$auth['type'];
        $this->assign('auth', $auth);  


        if(strstr($_SERVER['HTTP_USER_AGENT'],'MicroMessenger')){
          // 微信Jssdk 操作类 用分享朋友圈 JS            
               $jssdk = new \app\mobile\logic\Jssdk($this->weixin_config['appid'], $this->weixin_config['appsecret']);
               $signPackage = $jssdk->GetSignPackage();
               
              
               $this->assign('signPackage',$signPackage);
        }
        
        $this->public_assign();

    }

    

    /**

     * 保存公告变量到 smarty中 比如 导航 

     */   

    public function public_assign()

    {

       $tpshop_config = array();

       $tp_config = M('config')->cache(true,TPSHOP_CACHE_TIME)->select();       

       foreach($tp_config as $k => $v)

       {

       	  if($v['name'] == 'hot_keywords'){

       	  	 $tpshop_config['hot_keywords'] = explode('|', $v['value']);

       	  }       	  

          $tpshop_config[$v['inc_type'].'_'.$v['name']] = $v['value'];

       }                        

       

        $goods_category_tree = get_goods_category_tree();//获取商品分类
        $shop_category_tree = get_shop_category_tree();//获取店铺商品分类
        //var_dump($shop_category_tree);

       $this->cateTrre = $goods_category_tree;

       $this->assign('goods_category_tree', $goods_category_tree);   
       $this->assign('shop_category_tree', $shop_category_tree);                    

       $brand_list = M('brand')->cache(true,TPSHOP_CACHE_TIME)->field('id,cat_id,logo,is_hot')->where("cat_id>0")->select();              

       $this->assign('brand_list', $brand_list);

       $this->assign('tpshop_config', $tpshop_config);

    }      



     

    public function ajaxReturn($data){

        exit(json_encode($data));

    }


    //道讯销售记录同步
    public function sync_sell_list(){
            $user=$this->user;
            $mobile=$user['mobile'];
        if(!$mobile){
            $db=C('DX_DB');
            $goods_sn=I('post.goods_sn');
            $type=I('post.type');
            try {  
              $hostname = $db['hostname']; 
              $port = $db['port'];  
              $dbname = $db['dbname'];
              $username = $db['username'];  
              $pw = $db['pw']; 
              $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname;charset=GBK","$username","$pw");  
            } catch (PDOException $e) {  
              echo "Failed to get DB handle: " . $e->getMessage() . "\n";  
              exit;  
            }

           
        
        $sql="select * from (
        select 
         t0.SHOP_ID 
        ,t1.CUST_ID
        ,t1.CUST_CARD_NUM
        ,t5.unit_name 
        ,t0.RLB_NUM 
        ,t0.LINE_NUM  
        ,t0.PROD_ID  
        ,t3.PROD_CLS_NUM 
        ,t2.PROD_NUM  
        ,t3.PROD_NAME 
        ,t4.COLOR_NUM
        ,t4.COLOR_NAME
        ,t6.SPEC_NUM 
        ,t6.SPEC_NAME 
        ,t1.TRAN_TIME 
        ,t0.UNIT_PRICE 
        ,t0.DISC_RATE 
        ,t0.ORG_UNIT_PRICE 
        ,t0.ORG_DISC_RATE 
        ,t0.SELL_QTY  
        ,t0.SELL_VAL 
        ,t0.SELL_MODE 
        from RLB_DTL t0 left join RLB t1 on t0.RLB_NUM = t1.RLB_NUM and t0.SHOP_ID = t1.SHOP_ID
                         left join PRODUCT t2 on t0.prod_id = t2.prod_id
                         left join PROD_CLS t3 on t2.prod_cls_id = t3.prod_cls_id
                         left join PROD_COLOR t4 on t2.COLOR_ID = t4.COLOR_ID
                         left join SYS_UNIT t5 on t0.SHOP_ID = t5.UNIT_ID and t5.UNIT_PROP ='D'
                         left join PROD_SPEC t6 on t2.SPEC_ID = t6.SPEC_ID

        union all

        select t0.SHOP_ID,t3.CUST_ID,t3.CARD_NUM,t4.UNIT_NAME,t2.RLB_NUM,t2.LINE_NUM,t2.PROD_ID,t6.PROD_CLS_NUM,t5.PROD_NUM,t6.PROD_NAME,t7.COLOR_NUM,
                 t7.COLOR_NAME,t8.SPEC_NUM,t8.SPEC_NAME
                ,t0.TRAN_TIME 
                ,t2.UNIT_PRICE 
                ,t2.DISC_RATE  
                ,t2.ORG_UNIT_PRICE  
                ,t2.ORG_DISC_RATE 
                ,t2.SELL_QTY 
                ,t2.SELL_VAL 
                ,t2.SELL_MODE 
        from RLB t0 left join RLB_PAY t1 on t0.SHOP_ID = t1.SHOP_ID and t0.RLB_NUM = t1.RLB_NUM
                    left join RLB_DTL t2 on t0.SHOP_ID = t2.SHOP_ID and t0.RLB_NUM = t2.RLB_NUM 
                    left join CUST_CARD t3 on t1.CARD_NUM = t3.CARD_NUM
                    left join SYS_UNIT t4 on t0.SHOP_ID = t4.UNIT_ID and t4.UNIT_PROP = 'D'
                    left join PRODUCT t5 on t2.prod_id = t5.prod_id
                    left join PROD_CLS t6  on t5.prod_cls_id = t6.prod_cls_id
                    left join PROD_COLOR t7 on t5.COLOR_ID = t7.COLOR_ID
                    left join PROD_SPEC t8 on t5.SPEC_ID = t8.SPEC_ID     
                      where t0.CUST_CARD_NUM is null ) t 
                      where t.CUST_CARD_NUM = '".$mobile."'";
                
            //查询最近一次的交易时间
            $tran_time=M('cust_buy_log')->where(['user_id'=>$this->user_id])->order('tran_time desc')->limit(0,1)->getfield('tran_time');
            if($tran_time){
              $sql.=" and t.TRAN_TIME>'".date('M d Y h:i:s:000A',$tran_time)."'"; 
            }
            $stmt = $dbh->prepare($sql);
            $stmt->execute();

            //var_dump($sql);

            $total_sell_val=0;
            while ($row = $stmt->fetch()) {
                //print_r($row);
                $arr['user_id']=$this->user_id;
                $arr['shop_id']=$row['SHOP_ID'];
                $arr['cust_id']=$row['CUST_ID'];
                $arr['prod_id']=$row['PROD_ID'];
                $arr['cust_card_num']=$row['CUST_CARD_NUM'];
                $arr['unit_name']=iconv('GBK', 'UTF-8', $row['unit_name']);
                $arr['rlb_num']=$row['RLB_NUM'];
                $arr['line_num']=$row['LINE_NUM'];
                $arr['prod_cls_num']=$row['PROD_CLS_NUM'];
                $arr['prod_num']=$row['PROD_NUM'];
                $arr['prod_name']=iconv('GBK', 'UTF-8', $row['PROD_NAME']);
                $arr['color_num']=$row['COLOR_NUM'];
                $arr['color_name']=iconv('GBK', 'UTF-8', $row['COLOR_NAME']);
                $arr['spec_num']=$row['SPEC_NUM'];
                $arr['spec_name']=iconv('GBK', 'UTF-8', $row['SPEC_NAME']);
                $arr['tran_time']=strtotime($row['TRAN_TIME']);
                $arr['unit_price']=$row['UNIT_PRICE'];
                $arr['disc_rate']=$row['DISC_RATE'];
                $arr['org_unit_price']=$row['ORG_UNIT_PRICE'];
                $arr['org_disc_rate']=$row['ORG_DISC_RATE'];
                $arr['sell_qty']=$row['SELL_QTY'];
                $arr['sell_val']=$row['SELL_VAL'];
                $arr['sell_mode']=$row['SELL_MODE'];
                //echo date('M d Y h:i:s:000A',strtotime($row['TRAN_TIME']));
                //将同步数据写入数据库
                $res=M('cust_buy_log')->add($arr);

                //计算该次同步客户的总消费金额
                $total_sell_val+=$arr['sell_val']*100;
            }

            //将消费金额换算成积分同步到数据库
             if($total_sell_val){
                $points=$total_sell_val/100;
                $res=accountLog($this->user_id,0,$points,"门店购物返积分",0,"order");

                $res=M('users')->where('user_id',$this->user_id)->save(array("total_amount" => ["exp", "total_amount+" . $total_sell_val/100]));
              
                update_user_level($this->user_id);//更新会员等级

             }
             
            } 
            
        }




}